package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author Suave
 * @date 2024/8/17
 */
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
//        处理返回的时间数据
        List<LocalDate> dateTimeList = new ArrayList<>();
        dateTimeList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateTimeList.add(begin);
        }
//        处理营业额数据
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate dateTime : dateTimeList) {
//            获取当前的最早时间和最晚时间
            LocalDateTime beginTime = LocalDateTime.of(dateTime, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(dateTime, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.getTurnoverByMap(map);

            turnover = turnover == null ? 0 : turnover;
            turnoverList.add(turnover);
        }

        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateTimeList,","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户数量统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //        处理返回的时间数据
        List<LocalDate> dateTimeList = new ArrayList<>();
        dateTimeList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateTimeList.add(begin);
        }

//        新用户数量
        List<Integer> newUserList = new ArrayList<>();
//        总用户数量
        List<Integer> totalUserList = new ArrayList<>();

//        查询用户总数和新增用户数量
        for (LocalDate localDate : dateTimeList) {
//            当天最早时间
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
//            当天最晚时间
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
//            封装查询条件
            Map map = new HashMap();
            map.put("end",endTime);

//            查询总用户
            Integer totalUserCount = userMapper.getCountByMap(map);
            totalUserCount = totalUserCount == null ? 0 : totalUserCount;
            totalUserList.add(totalUserCount);

//            查询新增用户数量
            map.put("begin", beginTime);
            Integer newUserCount = userMapper.getCountByMap(map);
            newUserCount = newUserCount == null ? 0 : newUserCount;
            newUserList.add(newUserCount);
        }
        return UserReportVO
                .builder()
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .dateList(StringUtils.join(dateTimeList,","))
                .build();
    }

    /**
     * 统计订单数量
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
//        处理返回的时间数据
        List<LocalDate> dateTimeList = new ArrayList<>();
        dateTimeList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateTimeList.add(begin);
        }

//        有效订单
        List<Integer> validOrderCountList = new ArrayList<>();
//        总订单
        List<Integer> totalOrderCountList = new ArrayList<>();

//        处理有效订单和总订单
        for (LocalDate localDate : dateTimeList) {
//            当天最早时间
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
//            当天最晚时间
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            
//            封装查询数据
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            
//            查询当天总的订单数量
            Integer totalOrderCount =  orderMapper.getOrderCountByMap(map);
            totalOrderCount = totalOrderCount == null ? 0 : totalOrderCount;
            totalOrderCountList.add(totalOrderCount);
            
//            查询当天有效订单数量
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.getOrderCountByMap(map);
            validOrderCount = validOrderCount == null ? 0 : validOrderCount;
            validOrderCountList.add(validOrderCount);
        }
//        总的订单数
        Integer totalOrderCount = totalOrderCountList.stream().reduce(Integer::sum).get();
//        总的有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
//        订单完成率
        Double orderCompletionRate  = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount * 1.0 / totalOrderCount;
        }
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateTimeList,","))
                .orderCountList(StringUtils.join(totalOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 统计销量前10的菜品
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO salesTop10Statistics(LocalDate begin, LocalDate end) {
//        最早时间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
//        最晚时间
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end",endTime);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10ByMap(map);

        List<String> nameList = goodsSalesDTOList
                .stream()
                .map(GoodsSalesDTO::getName)
                .collect(Collectors.toList());

        List<Integer> numberList = goodsSalesDTOList
                .stream()
                .map(GoodsSalesDTO::getNumber)
                .collect(Collectors.toList());

        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 导出营业数据
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
//        查询数据库获取近30天的营业数据
//        获取近30天的时间
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
//        查询近30天的营业数据数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

//        通过POI向excel写入数据
        try {
//            导入excel模板
            InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
            XSSFWorkbook excel = new XSSFWorkbook(in);
//            获取sheet页
            XSSFSheet sheet = excel.getSheet("sheet1");
//            设置时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "-" + end);
//            设置概览数据
//            第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
//            第五行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

//            设置每天明细数据
//            从第一天开始遍历
            for (int i = 0; i < 30; i++) {
                LocalDate localDate = begin.plusDays(i);
//                查询明细数据
                BusinessDataVO todayBusinessData = workspaceService.getBusinessData(LocalDateTime.of(localDate, LocalTime.MIN), LocalDateTime.of(localDate, LocalTime.MAX));
//                设置当天明细数据
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(localDate.toString());
                row.getCell(2).setCellValue(todayBusinessData.getTurnover());
                row.getCell(3).setCellValue(todayBusinessData.getValidOrderCount());
                row.getCell(4).setCellValue(todayBusinessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(todayBusinessData.getUnitPrice());
                row.getCell(6).setCellValue(todayBusinessData.getNewUsers());

            }
            //                通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
//                关闭资源
            out.close();
            excel.close();
            in.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
